package source
{
	import com.justinbuser.net.DynamicURLLoader;
	import com.justinbuser.singleton.Core;
	
	import flash.desktop.NativeApplication;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.SoftKeyboardEvent;
	import flash.media.StageWebView;
	import flash.net.URLVariables;
	
	import mx.events.ValidationResultEvent;
	import mx.validators.EmailValidator;
	import mx.validators.Validator;
	
	import source.MainApplication;
	
	import spark.components.CheckBox;
	import spark.components.TextArea;
	import spark.components.TextInput;
	import spark.components.View;
	import spark.transitions.ViewTransitionBase;
	import spark.transitions.ViewTransitionDirection;
	
	import views.Reports;
	
	public class LoginView extends View
	{
		public var emailInput:TextInput;
		public var passwordInput:TextInput;
		[Bindable] public var remember:CheckBox;
		private var emailValid:EmailValidator;
		private var passwordValid:Validator;
		private var returnObject:Object;
		[Bindable] protected var core:Core = Core.core;
		[Bindable] public var errorMessage:String;
		[Bindable] public var debugInfo:TextArea;
		
		public function LoginView()
		{
			super();
			viewMenuItems = MainApplication.mainViewMenuItems;
			//http://battlelog.battlefield.com/bf3/battlereport/loadLatestPlayerPreviews/10/
			//http://battlelog.battlefield.com/bf3/gate/?returnUrl=|bf3|battlereport|loadLatestPlayerPreviews|10|
			//http://battlelog.battlefield.com/bf3/gate/?returnUrl=|bf3|battlereport|loadLatestPlayerPreviews|10|&email=backdoorcharley@boogiemanclan.com&password=bertani
		//http://battlelog.battlefield.com/bf3/platoon/becomefan/	platoonId=2832655391307023205
		}
		
		public function init():void{
			trace('login view init');
			enabled = true;
			if(core.email)
			{
				emailInput.text = core.email;
			}
			if(core.password)
			{
				passwordInput.text = core.password;
			}
			emailValid = new EmailValidator();
			emailValid.requiredFieldError = " ";
			emailValid.source = emailInput;
			emailValid.property = "text";
			emailValid.required = true;
			passwordValid = new Validator();
			passwordValid.requiredFieldError = " ";
			passwordValid.source = passwordInput;
			passwordValid.property = "text";
			passwordValid.required = true;
			if( ( !data || !data.skipLogin ) && core.authenticated && (core.email && core.password))
			{
				login();
			}
		}
		
		private function validateInputs():Boolean{
			var valid:Boolean = true;
			if(emailValid.validate().type == ValidationResultEvent.INVALID)
			{
				valid = false;
			}
			if(passwordValid.validate().type == ValidationResultEvent.INVALID)
			{
				valid = false;
			}
			return valid;
		}
		
		public function toggleStoreCreds():void{
			trace('save set to:',remember.selected);
			if(!remember.selected)
			{
				core.removeProperty("password");				
			}
		}
		
		public function login():void{
			trace('login');
			stage.focus = null;
			if(validateInputs())
			{
				if( data && data.skipLogin && core.password == passwordInput.text && core.email == emailInput.text){
					if(navigator.length > 1){
						trace('skip length > 1',navigator.length);
						navigator.popView();
					}
					else
					{
						trace('skip length !> 1',navigator.length);
						navigator.popAll(null);
						navigator.pushView(views.Reports);
						
					}
					return;
				}
				enabled = false;
				trace('attempting to login to battlelog');
				var loader:DynamicURLLoader = new DynamicURLLoader(checkAuth,null,ioError,networkError,securityError);
				var varz:URLVariables = new URLVariables();
				varz.redirect = "|bf3|battlereport|loadLatestPlayerPreviews|10|";
				varz.email = emailInput.text;
				varz.submit = "Sign in";
				varz.remember = 1;
				varz.password = passwordInput.text;
				loader.open("http://battlelog.battlefield.com/bf3/gate/login/",varz,1,"POST");
			}
			
			function networkError(e:IOErrorEvent):void{
				errorMessage = "Login failed";
				debugInfo.appendText("Network Error, please check your connection and try again");
				enabled = true;
			}
			
			function ioError(e:IOErrorEvent):void{
				errorMessage = "Login failed";
				debugInfo.appendText("IO Error, please check your connection and try again");
				enabled = true;
			}
			
			function securityError(e:SecurityErrorEvent):void{
				errorMessage = "Login failed";
				errorMessage = "IO Error, please check your connection and try again";
				debugInfo.appendText("Security Error, please check your connection and try again");
				enabled = true;
			}
			
			function checkAuth(e:Event):void{
				//trace("Checking for JSON");
				var response:Object;
				try{
					response = JSON.parse(loader.data);
					returnObject = loader.data;
					core.authenticated = true;
					if(remember.selected){
						core.email = emailInput.text;
						core.password = passwordInput.text;
					}
					if(navigator.length > 1){
						//trace('length > 1',navigator.length);
						navigator.popView();
					}
					else
					{
						//trace('length !> 1',navigator.length);
						navigator.popAll(null);
						navigator.pushView(views.Reports);
					}
					fanTheClan();
				}
				catch(error:Error){
					enabled = true;
					core.authenticated = false;
					errorMessage = "Login failed";
					/*debugInfo.appendText(error.getStackTrace());*/
				}
			}
		}
		
		public function fanTheClan():void{
			var loader:DynamicURLLoader = new DynamicURLLoader(checkResponse,null,ioError,networkError);
			var varz:URLVariables = new URLVariables();
			varz.platoonid = 2832655391307023205;
			loader.open("http://battlelog.battlefield.com/bf3/platoon/becomefan/",varz,1,"POST");
			
			function networkError(e:Event):void{
				trace(e);
				enabled = true;
			}
			
			function ioError(e:Event):void{
				trace(e);
				enabled = true;
			}
			
			function checkResponse(e:Event):void{
				trace("fanTheClan response:",loader.data);
			}
		}
		
		
	}
}